package logic

import (
	"cloud-disk/core/helper"
	"cloud-disk/core/internal/svc"
	"cloud-disk/core/internal/types"
	"cloud-disk/tool"
	"context"
	"fmt"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type MailCodeSendLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMailCodeSendLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MailCodeSendLogic {
	return &MailCodeSendLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MailCodeSendLogic) MailCodeSend(req *types.MailCodeSendRequest) (resp *types.MailCodeSendResponse, err error) {
	resp = new(types.MailCodeSendResponse)

	count, err := l.svcCtx.UserModel.GetUserCountByEmail(req.Email)
	if err != nil {
		resp.Message = "发送验证码失败" + err.Error()
		resp.Code = 100
		return resp, nil
	}

	if count != 0 {
		resp.Message = "该邮箱已被注册"
		resp.Code = 100
		return resp, nil
	}

	verifyKey := helper.Md5(fmt.Sprintf("%s-%s", req.Email, helper.RandAllString(36))) // 密钥
	code := helper.RandCode(l.svcCtx.Config.CodeLength)
	tool.Cache.Set(verifyKey, code, time.Duration(l.svcCtx.Config.CodeExpire)*time.Second)
	err = l.svcCtx.Email.SendCode(req.Email, code)
	if err != nil {
		resp.Message = "发送验证码失败" + err.Error()
		resp.Code = 100
		return resp, nil
	}
	resp.Message = "发送验证码成功"
	resp.Code = 200
	resp.VerifyKey = verifyKey
	return resp, nil
}
